﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Collections;
using System.Net;

namespace Portal
{

    public class IP_Location
    {
        private string m_Location = "", m_IpAddress = "", m_Response = "";
        /// <summary>
        /// 新建IpLocation实例以获得IP地理位置
        /// </summary>
        /// <param name="ipAddress"></param>
        public IP_Location(string ipAddress)
        {
            m_IpAddress = ipAddress.Trim();

            //string[] ip = ipAddress.Split('.');
            // ipAddress = ip[0] + "." + ip[1] + ".1.1";
            //http://opendata.baidu.com/api.php?query=122.228.159.250&co=&resource_id=6006&t=1346136470458&ie=utf8&oe=gbk&cb=bd__cbs__7o8i84&format=json&tn=baidu
            var client = new WebClient();
            client.Encoding = System.Text.Encoding.GetEncoding("GB2312");

            string url = "http://opendata.baidu.com/api.php";
            // string post = "ip=" + ipAddress + "&action=2";
            //  string url = "http://www.ip138.com/ips1388.asp";
            string post = "query=" + ipAddress + "&co=&resource_id=6006&t=1346136470458&ie=utf8&oe=gbk&cb=bd__cbs__7o8i84&format=json&tn=baidu";
            client.Headers.Set("Content-Type", "application/x-www-form-urlencoded");
            string response = client.UploadString(url + "?" + post, "POST", post);
            m_Response = response;

            //string p = @"<li>参考数据二：(?<location>[^<>]+?)</li>";

            //Match match = Regex.Match(response, p);
            //  m_Location = match.Groups["location"].Value.Trim();
            m_Location = response;
        }

        /// <summary>
        /// 返回Ip地址的地理位置名称
        /// </summary>
        public string Location
        {
            get
            {
                return m_Location;
            }
        }

        public string IpAddress
        {
            get
            {
                return m_IpAddress;
            }
        }

        /// <summary>
        /// 返回网络反馈原始数据
        /// </summary>
        public string Response
        {
            get
            {
                return m_Response;
            }
        }

        public string getAddress()
        {
            return m_Location;
        }
    }

}
